package com.wiz.weixin.controllor;

import java.io.UnsupportedEncodingException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wiz.weixin.common.ResponseCode;
import com.wiz.weixin.manager.CodeManager;
import com.wiz.weixin.manager.TencentManager;
import com.wiz.weixin.manager.WxAccessManager;
import com.wiz.weixin.service.WeixinConfigService;
import com.wiz.weixin.util.TencentUtil;

@Controller
@RequestMapping("/tencent")
public class TencentControllor {
	private transient final Logger log = LoggerFactory.getLogger(getClass());
	
	@Resource
	private TencentManager tencentManager;
	@Resource
	private WxAccessManager wxAccessManager;
	@Resource
	private CodeManager codeManager;
	@Resource
	private WeixinConfigService weixinConfigService;
	
	@RequestMapping(value="", method=RequestMethod.GET)
	@ResponseBody
	public String signature(HttpServletRequest request,HttpServletResponse response,
			HttpSession session, Model model){
		String signature = request.getParameter("signature");//签名串
		String timestamp =  request.getParameter("timestamp");//时间戳
		String nonce =  request.getParameter("nonce"); //随机数
		String echostr =  request.getParameter("echostr"); //随机字符串
		boolean b = TencentUtil.checkSignature(signature, timestamp, nonce);
		if(b){
			return echostr;
		}
		return "error";
	}
	
	@RequestMapping(value="", method=RequestMethod.POST)
	@ResponseBody
	public String handleMessage(HttpServletRequest request,HttpServletResponse response,
			HttpSession session, Model model) throws UnsupportedEncodingException{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		return tencentManager.processRequest(request);
	}
	
	@RequestMapping(value="/menu", method=RequestMethod.GET)
	@ResponseBody
	public String createMenu(HttpServletRequest request,HttpServletResponse response,
			HttpSession session, Model model) throws JSONException{
		return tencentManager.createMenu();
	}
	
	@RequestMapping(value="/token", method=RequestMethod.GET)
	@ResponseBody
	public String resetToken(HttpServletRequest request,HttpServletResponse response,
			HttpSession session, Model model) throws Exception{
		if(wxAccessManager.resetWxToken()){
			if(wxAccessManager.resetJsApiTicket()){
				return ResponseCode.DATA_OK;
			}
		}
		return ResponseCode.SERVER_ERROR;
	}
	
	/**
	 * 生成永久二维码
	 * @param type 1=临时二维码;2=永久二维码;3=永久的字符串参数二维码
	 * */
	@RequestMapping(value="/generatedCode", method=RequestMethod.GET)
	@ResponseBody
	private String generatedCode(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "type") int type,
			@RequestParam(value = "sceneStr",required = false) String sceneStr,
			@RequestParam(value = "sceneId",required = false) String sceneId,
			HttpSession session, Model model){
		if(type == 0){
			return "{\"code\":300,\"msg\":\"error param type\"}";
		}
		String result = null;
		JSONObject responseJson;
		try {
			responseJson = codeManager.getTicket(type,sceneStr,sceneId);
			if(!responseJson.isNull("ticket")){
				String ticket = responseJson.getString("ticket");
//				String url = responseJson.getString("url");
				result = "{\"code\":200,\"msg\":\"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+ticket+"\","
						+ "\"url\":\""+responseJson.getString("url")+"\"}";
			}else{
				result = "{\"code\":300,\"msg\":\"invalid appid\"}";
			}
			return result;
		} catch (Exception e) {
			log.error("generatedCode happen error : "+e.toString());
			return ResponseCode.SERVER_ERROR;
		}
	}
	
	/**
	 * 长链接转短链接
	 * https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5d7213f7ae8e6fdf&amp;redirect_uri=http%3A%2F%2Fwx.wiz-tech.com.cn%2FscanRefueling%2FtoAuthorization%0f%3ffpId%3d10031&amp;response_type=code&amp;scope=snsapi_base&amp;state=123#wechat_redirect
	 * 
	 * */
	@RequestMapping(value="/shortURL" , method=RequestMethod.POST)
	@ResponseBody
	public String shortURL(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "url") String url,
			HttpSession session, Model model){
		return tencentManager.shortURL(url);
	}

	/**
	 * 朋友圈分享
	 */
	@RequestMapping(value="/weixinShare" , method=RequestMethod.GET)
	public String weixinShare(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "stationId") String stationId,
			HttpSession session, Model model){
		model.addAttribute("wxConfig", weixinConfigService.getWxConfigByHqId(stationId));
		return "/member/wxshare";
	}
}
